package com.wcbtest.dem02.controller;

import com.jcraft.jsch.JSchException;
import com.wcbtest.dem02.entity.*;
import com.wcbtest.dem02.service.TopCommandExecutor;
import com.wcbtest.dem02.service.TopOutputParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/system")
@Api(value = "系统信息API", tags = "系统监控")
public class SystemInfoController {

    @Autowired
    private TopCommandExecutor commandExecutor;

    @Autowired
    private TopOutputParser outputParser;

    @PostMapping("/all")
    @ApiOperation(value = "获取完整系统信息", notes = "通过SSH执行top命令并解析结果")
    public SystemInfo getSystemInfo() throws JSchException, IOException {
        String topOutput = execCommand();
        return outputParser.parseTopOutput(topOutput);
    }


    @PostMapping("/cpu")
    @ApiOperation(value = "获取CPU信息", notes = "通过SSH执行top命令并解析CPU相关信息")
    public CpuInfo getCpuInfo() throws JSchException, IOException {
        String topOutput = execCommand();
        return outputParser.parseTopOutput(topOutput).getCpuInfo();
    }

    @PostMapping("/memory")
    @ApiOperation(value = "获取内存信息", notes = "通过SSH执行top命令并解析内存相关信息")
    public MemoryInfo getMemoryInfo() throws JSchException, IOException {
        String topOutput = execCommand();
        return outputParser.parseTopOutput(topOutput).getMemoryInfo();
    }

    @PostMapping("/processes")
    @ApiOperation(value = "获取进程列表", notes = "通过SSH执行top命令并解析进程相关信息")
    public List<ProcessInfo> getProcesses() throws JSchException, IOException {
        String topOutput = execCommand();
        return outputParser.parseTopOutput(topOutput).getProcessList();
    }

    private String execCommand() throws JSchException, IOException {
        SshResult sshResult = commandExecutor.executeTopCommand();
        if (sshResult.isSuccess()) {
            return sshResult.getStdout();
        } else {
            return sshResult.getStderr();
            //return new RuntimeException(sshResult.toString());
        }
    }

}    